﻿using AutoMapper;
using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.ReadAPI.Applications.Commands.Depts;
using B.S.Meeting.ReadAPI.Dtos;
using MediatR;

namespace B.S.Meeting.ReadAPI.Applications.CommandHandlers.Depts
{
    public class GetDeptCommandHandler : IRequestHandler<GetDeptCommand, APIResult<APIPaging<List<DeptDto>>>>
    {
        IBaseRepository<User> uRep;
        IBaseRepository<Dept> dRep;
        IMapper mapper;
        ILogger<GetDeptCommandHandler> logger;

        public GetDeptCommandHandler(IBaseRepository<Dept> dRep, IMapper mapper, ILogger<GetDeptCommandHandler> logger, IBaseRepository<User> uRep)
        {
            this.dRep = dRep;
            this.mapper = mapper;
            this.logger = logger;
            this.uRep = uRep;
        }

        public async Task<APIResult<APIPaging<List<DeptDto>>>> Handle(GetDeptCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var deptlist= dRep.GetAll().Where(x=>!x.IsDel);
                var userlist = uRep.GetAll().Where(x => !x.IsDel);
                if (!string.IsNullOrEmpty(request.DeptName))
                {
                    deptlist = deptlist.Where(x=>x.DeptName.Contains(request.DeptName));
                }
                var list = from d in deptlist
                           join u in userlist
                           on d.UserId equals u.UserId
                           select d;
                var totalCount= list.Count();
                var totalPage=(int)Math.Ceiling(totalCount*1.0/request.PageSize);
                list=list.OrderBy(x=>x.DeptId).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize);
                List<DeptDto> deptdto =mapper.Map<List<DeptDto>>(list);
                List<User> users = uRep.GetAll().ToList();
                foreach (var item in deptdto)
                {
                    item.UserName = users.Find(x=>x.UserId==item.UserId).UserName;
                }
                return new APIResult<APIPaging<List<DeptDto>>>
                {
                    Code=StatusEnumCode.Ok,
                    Message="获取部门列表成功",
                    Data=new APIPaging<List<DeptDto>>
                    {
                        TotalCount=totalCount,
                        TotalPage=totalPage,
                        Data=deptdto
                    }
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
